using System;
using System.ComponentModel;
using System.Reflection;
using GaDotNet.Common.Data;
using Microsoft.SmallBasic.Library;
using SmallBasicFun.Analytics;
using SmallBasicFun.Tracking;

namespace SmallBasicFun
{
	public class GoogleAnalyticsTrack : ITrackingEvent
	{
		private bool finished = false;

		public CancelEventHandler CaptureClosingEvent()
		{
			return delegate { Track(); };
		}

		public void Track()
		{
			if (finished)
			{
				return;
			}
			GetTrackingRequest().FireTrackingEvent();
			finished = true;
		}

		public TrackingRequest GetTrackingRequest()
		{
			var g = new GooglePageView("TKP", "www.tkp.net", GetPageName());
			var tr = new TrackingRequest(g) {AnalyticsAccountCode = "UA-38838212-2"};
			return tr;
		}

		private string GetPageName()
		{
			try
			{
				var entryAssembly = Assembly.GetEntryAssembly();
				var entryPoint = entryAssembly.EntryPoint;
				var declaringType = entryPoint.DeclaringType;
				return "/" + declaringType.Name;
			}
			catch (Exception)
			{
				return "/unknown";
			}
		}


		public SmallBasicCallback CaptureInactiveEvent()
		{
			return DoNothing;
		}

		public void Abort()
		{
			finished = true;
		}

		protected void DoNothing()
		{
		}
	}
}